<?php

namespace addons\fastworker\library\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Worker;

/**
 * Fastworker Timer 命令行类
 */
class Timer extends Command
{

    protected $config;
    protected $timer;

    public function configure()
    {
        $this->setName('fastworker:timer')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('interval', 'i', Option::VALUE_OPTIONAL, 'Timer task interval', null)
            ->addOption('execution', 'exec', Option::VALUE_OPTIONAL , 'Timer task execution', null)
            ->addOption('daemon', 'd', Option::VALUE_NONE, 'Run Timer in daemon mode.')
            ->addOption('single', 's', Option::VALUE_NONE, 'Run Timer in single mode.')
            ->setDescription('Fastworker Timer : timed task');

    }

    public function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');

        if (DIRECTORY_SEPARATOR !== '\\') {
            if (!in_array($action, ['start', 'stop', 'reload', 'restart', 'status', 'connections'])) {
                $output->writeln("<error>Invalid argument action:{$action}, Expected start|stop|restart|reload|status|connections .</error>");
                return false;
            }

            global $argv;
            array_shift($argv);
            array_shift($argv);
            array_unshift($argv, 'think', $action);
        } elseif ('start' != $action) {
            $output->writeln("<error>Not Support action:{$action} on Windows.</error>");
            return false;
        }

        $this->config = [
            'count'          => 1,   //单进程,多进程可能会造成并发问题
            'daemonize'      => $this->input->hasOption('daemon'),

            'onWorkerStart'  => [$this,'startTimer'],

            'onClose'        => function ($connection) {
                \Workerman\Lib\Timer::del($this->timer);
            },
            'onError'        => function ($connection, $code, $msg) {
                echo "error [ $code ] $msg\n";
            },
        ];

        if ('start' == $action) {
            $output->writeln('Starting Timer...');
        }

        $worker = new Worker();

        // 设置Worker参数
        foreach ($this->config as $name => $val) {
            if (in_array($name, ['daemonize'])) {
                Worker::${$name} = $val;
            } else {
                $worker->$name = $val;
            }
        }

        Worker::runAll();
    }

    public function startTimer()
    {
        $execution = $this->getOption('execution','addons\\fastworker\\example\\Timer.fire');
        if(stripos($execution,'.')){
            list($execution,$method) = explode('.',$execution);
        }else{
            $method = 'fire';
        }
        if (class_exists($execution)) {
            $class = new $execution;
            if(!method_exists($class,$method)){
                $this->output->writeln("<error>Method Not Exists: {$method}</error>");
                return false;
            }

        } else {
            $this->output->writeln("<error>Class Not Exists : {$execution}</error>");
            return false;
        }

        $this-> timer = \Workerman\Lib\Timer::add($this->getOption('interval',10),[$class,$method],[],!$this->input->hasOption('single'));
    }

    protected function getOption($name,$default){
        if ($this->input->hasOption($name)) {
            return $this->input->getOption($name);
        }
        return $default;
    }
}
